package com.codecrane.core.power.controller;

import com.codecrane.core.power.entity.PowerUser;
import com.codecrane.core.power.service.PowerUserService;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.management.ManagementFactory;

/**
 * 系统容器管理
 * Created by crane on 17/3/22.
 */
@Slf4j
@Controller
@RequestMapping("/power/container")
public class ContainerManagerController {

    @Autowired
    private PowerUserService powerUserService;

    /**
     * 管理页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String managerPage(ModelMap model) {
        return "/power/system/main";
    }

    /**
     * 重启容器服务器
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/restart", method = RequestMethod.POST)
    public AjaxReturn restartContainer(HttpServletRequest request) {

        AjaxReturn webResult = Ajax.fail().setMsg("重启失败!");


        PowerUser user = powerUserService.getCurrentUserFromShiro();
        if (null != user && "admin".equals(user.getUserAccount())) {

            String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
            String deployPath = request.getServletContext().getRealPath("");
            String binPath = deployPath.substring(0, deployPath.lastIndexOf("webapps")) + "bin";
            log.debug("deployPath:{}", deployPath);
            log.debug("binPath:{}", binPath);
            StringBuffer sb = new StringBuffer();
            try {

                Runtime rt = Runtime.getRuntime();
                String unixCmds[] = new String[]{"/bin/sh", "-c", "cd " + binPath + ";./shutdown.sh;./startup.sh"};
                Process process = null;
                if (SystemUtils.IS_OS_WINDOWS) {

                    //生成bat文件
                    File restart = new File(binPath + "\\restart.bat");
                    String cmds = "call taskkill /F /PID " + pid + " && call ping -n 5 127.0.0.1>null && call " + binPath + "\\catalina.bat start";

                    FileOutputStream stream = new FileOutputStream(restart);
                    stream.write(cmds.getBytes());
                    stream.flush();
                    stream.close();

                    //生成vbs文件
                    File restartVbs = new File(binPath + "\\restart.vbs");
                    String vbs = "Set ws = CreateObject(\"Wscript.Shell\") \n"
                            + "ws.run \"cmd /c restart.bat\",0";
                    stream = new FileOutputStream(restartVbs);
                    stream.write(vbs.getBytes());
                    stream.flush();
                    stream.close();

                    process = rt.exec("cmd /c start " + binPath + "\\restart.vbs");
                } else {
                    process = rt.exec(unixCmds);
                }

                BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = "";
                while ((line = read.readLine()) != null) {
                    sb.append(line);
                }
                read.close();
                webResult.setOk(true).setMsg(sb.toString());
            } catch (IOException e) {
                e.printStackTrace();
                webResult.setMsg("重启异常!");
                log.error("重新启动异常! {}", e.getMessage());
            }
        } else {
            webResult.setMsg("非法的用户操作!");
        }

        return webResult;
    }

}
